package com.itheima.algorithm.search;

public class BinarySearchDemo {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6,7,8,9};
        int number = 3;
        int index = binarySearchForIndex(arr,number);
        System.out.println("index = " + index);
    }

    private static int binarySearchForIndex(int[] arr,int number) {
        //定义查找范围
        int min = 0;
        int max = arr.length - 1;
        //循环查找
        while (min <= max){
            //计算中间索引
            int mid = (min + max) >> 1;     //位移运算  num/2
            if (arr[mid] > number){
                //number小于mid指向的元素  要查找的元素在左边
                max = mid - 1;
            }else if (arr[mid] < number){
                //number大于mid指向的元素  要查找的元素在右边
                min = mid + 1;
            }else {
                //number等于mid指向的元素  找到返回索引
                return mid;
            }
        }
        return -1;
    }

}
